const { poolQuery } = require("../utils/db");
const JWT = require("../utils/JWT");
const bcrypt = require("bcryptjs");
const loginModel = require("../models/loginModel");
const loginService = {
  // 登录校验
  loginUser: (account, password, res) => {
    poolQuery(loginModel.checkUserName, [account], (err, data) => {
      if (err) return res.tip(err);
      if (!data || data.length === 0) return res.tip("用户名不存在");
      const comparePassword = bcrypt.compareSync(password, data[0].password);
      if (!comparePassword) return res.tip("密码错误");
      const loginData = { ...data[0], password: "" };
      const tokenStr = JWT.generate(loginData);
      return res.send({
        code: 0,
        data: {
          ...loginData,
          access_token: "Bearer " + tokenStr,
        },
        message: "登录成功",
      });
    });
  },
};
module.exports = loginService;
